package com.example.musicplayer;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

// 在文件顶部添加
import android.app.AlertDialog;
import android.provider.Settings;
import android.content.pm.PackageManager;
import android.os.Build;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;

public class MusicPlayerActivity extends AppCompatActivity implements MediaPlayer.OnCompletionListener {

    private MediaPlayer mediaPlayer;
    private ArrayList<Song> songList;
    private ListView songListView;
    private SongAdapter songAdapter;
    private int currentSongIndex = -1;

    // 播放控制组件
    private ImageButton playPauseButton;
    private ImageButton nextButton;
    private ImageButton prevButton;
    private TextView currentTimeTextView;
    private TextView totalTimeTextView;
    private SeekBar seekBar;
    private TextView songTitleTextView;
    private TextView artistTextView;

    private Handler handler = new Handler();

    // 添加权限请求常量
    private static final int REQUEST_PERMISSION_CODE = 100;
    
    // 在onCreate方法中添加权限检查
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music_player);
    
        // 初始化视图组件
        initViews();
    
        // 检查权限
        if (checkPermission()) {
            // 权限已授予，加载音乐列表
            loadSongs();
        } else {
            // 权限未授予，请求权限
            requestPermission();
        }
    
        // 设置列表点击事件
        setListViewClickListener();
    
        // 初始化MediaPlayer
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setOnCompletionListener(this);
    
        // 设置进度条更新
        setupSeekBar();
    }

    private void initViews() {
        songListView = findViewById(R.id.song_list_view);
        playPauseButton = findViewById(R.id.play_pause_button);
        nextButton = findViewById(R.id.next_button);
        prevButton = findViewById(R.id.prev_button);
        currentTimeTextView = findViewById(R.id.current_time);
        totalTimeTextView = findViewById(R.id.total_time);
        seekBar = findViewById(R.id.seek_bar);
        songTitleTextView = findViewById(R.id.song_title);
        artistTextView = findViewById(R.id.artist);
    }

    // 从设备加载音乐
    private void loadSongs() {
        songList = new ArrayList<>();

        ContentResolver contentResolver = getContentResolver();
        Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;

        // 添加筛选条件，只查询音乐文件
        String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
        String sortOrder = MediaStore.Audio.Media.TITLE + " ASC";

        // 查询音乐文件
        Cursor cursor = contentResolver.query(uri, null, selection, null, sortOrder);

        if (cursor != null && cursor.moveToFirst()) {
            int titleColumn = cursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
            int artistColumn = cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);
            int dataColumn = cursor.getColumnIndex(MediaStore.Audio.Media.DATA);
            int durationColumn = cursor.getColumnIndex(MediaStore.Audio.Media.DURATION);
            int albumColumn = cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM);

            do {
                String title = cursor.getString(titleColumn);
                String artist = cursor.getString(artistColumn);
                String data = cursor.getString(dataColumn);
                long duration = cursor.getLong(durationColumn);
                String album = cursor.getString(albumColumn);

                // 过滤掉过短的音频文件（少于5秒）
                if (duration > 5000) {
                    songList.add(new Song(title, artist, album, data, duration));
                }
            } while (cursor.moveToNext());

            cursor.close();
        }

        // 设置适配器
        songAdapter = new SongAdapter(this, songList);
        songListView.setAdapter(songAdapter);

        // 如果列表为空，显示提示
        if (songList.isEmpty()) {
            Toast.makeText(this, "未找到音乐文件", Toast.LENGTH_SHORT).show();
        }
    }

    private void setListViewClickListener() {
        songListView.setOnItemClickListener((parent, view, position, id) -> {
            if (position == currentSongIndex && mediaPlayer.isPlaying()) {
                // 点击正在播放的歌曲，暂停
                pauseMusic();
                return;
            }

            // 播放选中的歌曲
            currentSongIndex = position;
            playMusic(currentSongIndex);
        });

        songListView.setOnItemLongClickListener((parent, view, position, id) -> {
            // 长按显示歌曲详情
            Song song = songList.get(position);
            showSongDetails(song);
            return true;
        });
    }

    // 播放音乐
    private void playMusic(int index) {
        if (index >= 0 && index < songList.size()) {
            Song song = songList.get(index);

            try {
                // 重置MediaPlayer并设置数据源
                mediaPlayer.reset();
                mediaPlayer.setDataSource(song.getPath());
                mediaPlayer.prepare();
                mediaPlayer.start();

                // 更新UI
                updatePlaybackUI(song);
                playPauseButton.setImageResource(R.drawable.ic_pause);

                // 更新进度条
                updateSeekBar();

            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(this, "无法播放此歌曲: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                // 尝试播放下一首
                onNextClick(null);
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(this, "播放出错: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }
    }

    // 暂停音乐
    private void pauseMusic() {
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
            playPauseButton.setImageResource(R.drawable.ic_play);
        }
    }

    // 播放/暂停按钮点击事件
    public void onPlayPauseClick(View view) {
        if (currentSongIndex == -1 && !songList.isEmpty()) {
            // 如果没有选中歌曲且列表不为空，播放第一首
            currentSongIndex = 0;
            playMusic(currentSongIndex);
        } else if (mediaPlayer.isPlaying()) {
            pauseMusic();
        } else {
            mediaPlayer.start();
            playPauseButton.setImageResource(R.drawable.ic_pause);
            updateSeekBar();
        }
    }

    // 下一首按钮点击事件
    public void onNextClick(View view) {
        if (!songList.isEmpty()) {
            currentSongIndex = (currentSongIndex + 1) % songList.size();
            playMusic(currentSongIndex);
        }
    }

    // 上一首按钮点击事件
    public void onPrevClick(View view) {
        if (!songList.isEmpty()) {
            currentSongIndex = (currentSongIndex - 1 + songList.size()) % songList.size();
            playMusic(currentSongIndex);
        }
    }

    // 更新播放UI
    private void updatePlaybackUI(Song song) {
        songTitleTextView.setText(song.getTitle());
        artistTextView.setText(song.getArtist());

        // 设置总时长
        String totalTime = formatTime(song.getDuration());
        totalTimeTextView.setText(totalTime);

        // 更新进度条最大值
        seekBar.setMax((int) song.getDuration());
    }

    // 格式化时间（毫秒 -> mm:ss）
    private String formatTime(long milliseconds) {
        return String.format("%02d:%02d",
                TimeUnit.MILLISECONDS.toMinutes(milliseconds),
                TimeUnit.MILLISECONDS.toSeconds(milliseconds) -
                        TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(milliseconds))
        );
    }

    // 设置进度条
    private void setupSeekBar() {
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser && mediaPlayer != null) {
                    mediaPlayer.seekTo(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {}

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {}
        });
    }

    // 更新进度条
    private void updateSeekBar() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                    int currentPosition = mediaPlayer.getCurrentPosition();
                    seekBar.setProgress(currentPosition);
                    currentTimeTextView.setText(formatTime(currentPosition));
                    handler.postDelayed(this, 1000);
                }
            }
        }, 1000);
    }

    // 显示歌曲详情
    private void showSongDetails(Song song) {
        Intent intent = new Intent(this, SongDetailActivity.class);
        intent.putExtra("title", song.getTitle());
        intent.putExtra("artist", song.getArtist());
        intent.putExtra("album", song.getAlbum());
        intent.putExtra("duration", formatTime(song.getDuration()));
        intent.putExtra("path", song.getPath());
        startActivity(intent);
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        // 当前歌曲播放完成，自动播放下一首
        onNextClick(null);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
        }
        handler.removeCallbacksAndMessages(null);
    }

// 检查权限
private boolean checkPermission() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
        // Android 13及以上
        return ContextCompat.checkSelfPermission(this, Manifest.permission.READ_MEDIA_AUDIO) == PackageManager.PERMISSION_GRANTED;
    } else {
        // Android 12及以下
        return ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
    }
}

// 请求权限
private void requestPermission() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
        // Android 13及以上
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_MEDIA_AUDIO}, REQUEST_PERMISSION_CODE);
    } else {
        // Android 12及以下
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_PERMISSION_CODE);
    }
}

// 处理权限请求结果
@Override

public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == REQUEST_PERMISSION_CODE) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // 权限已授予
            loadSongs();
        } else {
            // 权限被拒绝
            Toast.makeText(this, "需要存储权限才能访问音乐文件", Toast.LENGTH_SHORT).show();
            // 可以选择关闭应用或引导用户到设置页面开启权限
            finish();
        }
    }
}
    // 获取当前播放的歌曲索引，供适配器使用
    public int getCurrentSongIndex() {
        return currentSongIndex;
    }
}